package com.mantru.iotpot.Util

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Log
import android.widget.ImageView
import com.squareup.picasso.Picasso
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.File
import java.io.FileOutputStream
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

object InternalFileSaver {
    // 压缩参数配置
    private const val TARGET_WIDTH = 1024 // 目标最大宽度
    private const val TARGET_HEIGHT = 1024 // 目标最大高度
    private const val COMPRESS_QUALITY = 80 // 压缩质量 (0-100)

    fun saveToPrivateFile(
        context: Context,
        imageUrl: String,
        fileName: String = "v001.png",
        callback: (success: Boolean) -> Unit
    ) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                // 1. 下载原始图片
                val client = OkHttpClient()
                val request = Request.Builder().url(imageUrl).build()
                val response = client.newCall(request).execute()

                response.body?.use { body ->
                    // 2. 解码并压缩图片
                    val originalBytes = body.bytes()
                    val compressedBitmap = decodeAndCompressBitmap(originalBytes)

                    // 3. 保存压缩后的图片
                    val file = File(context.filesDir, fileName)
                    FileOutputStream(file).use { fos ->
                        compressedBitmap?.compress(
                            Bitmap.CompressFormat.JPEG, // 强制转为JPEG格式压缩
                            COMPRESS_QUALITY,
                            fos
                        )
                    }
                    compressedBitmap?.recycle()
                }

                withContext(Dispatchers.Main) {
                    callback(true)
                }
            } catch (e: Exception) {
                e.printStackTrace()
                withContext(Dispatchers.Main) {
                    callback(false)
                }
            }
        }
    }

    // 核心压缩方法
    private fun decodeAndCompressBitmap(originalBytes: ByteArray): Bitmap? {
        // 第一步：计算采样率
        val options = BitmapFactory.Options().apply {
            inJustDecodeBounds = true
        }
        BitmapFactory.decodeByteArray(originalBytes, 0, originalBytes.size, options)

        // 计算缩放比例
        val (width, height) = options.outWidth to options.outHeight
        val scaleFactor = calculateScaleFactor(width, height)

        // 第二步：实际解码
        options.inJustDecodeBounds = false
        options.inSampleSize = scaleFactor
        options.inPreferredConfig = Bitmap.Config.RGB_565 // 减少内存占用

        val scaledBitmap = BitmapFactory.decodeByteArray(originalBytes, 0, originalBytes.size, options)

        // 第三步：质量压缩
        return scaledBitmap?.let { bitmap ->
            if (bitmap.width > TARGET_WIDTH || bitmap.height > TARGET_HEIGHT) {
                // 二次尺寸压缩
                val finalWidth = (bitmap.width * 0.8f).toInt().coerceAtMost(TARGET_WIDTH)
                val finalHeight = (bitmap.height * 0.8f).toInt().coerceAtMost(TARGET_HEIGHT)
                Bitmap.createScaledBitmap(bitmap, finalWidth, finalHeight, true)
            } else {
                bitmap
            }
        }
    }

    // 计算缩放因子
    private fun calculateScaleFactor(width: Int, height: Int): Int {
        var scale = 1
        while (width / (scale * 2) >= TARGET_WIDTH && height / (scale * 2) >= TARGET_HEIGHT) {
            scale *= 2
        }
        return scale
    }

    // 从私有目录加载图片（示例）
    fun loadPrivateImage(context: Context, fileName: String, imageView: ImageView) {
        val file = File(context.filesDir, fileName)
        if (file.exists()) {
            Picasso.get().load("file://" + file.absolutePath).into(imageView)
        }
    }
}